package com.heima.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.BaseContext;
import com.heima.common.JwtConfig;
import com.heima.exception.ErrorCode;
import com.heima.exception.GlobalException;
import com.heima.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 登录接口和静态资源放行
        String uri = request.getRequestURI();
        if (uri.contains("/login") || uri.endsWith(".html") || uri.endsWith(".css") || uri.endsWith(".js")) {
            return true;
        }

        String token = request.getHeader(jwtConfig.getAdminTokenName());
        if (StringUtils.isBlank(token)) {
            throw new GlobalException(ErrorCode.UNAUTHORIZED); // 返回未登录异常
        }

        try {
            Claims claims = jwtUtil.parseToken(token);
            // 可以把用户ID存到 ThreadLocal，方便后续获取
            BaseContext.setCurrentId(Long.valueOf(claims.getSubject()));
            return true;
        } catch (Exception e) {
            throw new GlobalException(ErrorCode.TOKEN_INVALID); // token解析失败
        }
    }
}
